class Item < ActiveRecord::Base
  belongs_to :category

  before_validation :assign_number_from_last_category, :on => :create

  validates :number, :uniqueness => {:scope => :category_id}
  validates_presence_of :title, :category, :number

  def assign_number_from_last_category
    max = Item.maximum(:number, :conditions  => ['category_id = ?', self.category_id])
    self.number = max+1 rescue 0
  end
end